package portal.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import java.net.URL;
import java.net.URLConnection;

import java.util.Date;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import oracle.stellent.ridc.IdcClient;

import oracle.stellent.ridc.IdcClientException;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;
import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.content.integration.*;
import oracle.webcenter.content.integration.federated.*;
import oracle.webcenter.content.integration.ContentContext;
import oracle.webcenter.content.integration.Node;
import oracle.webcenter.content.integration.RepositoryException;
import oracle.webcenter.content.integration.federated.ContentManagerFactory;
import oracle.webcenter.content.integration.federated.INodeManager;
import oracle.webcenter.content.integration.federated.internal.ContentContextHelper;
import oracle.webcenter.content.integration.federated.internal.delegate.IUCMContext;
import oracle.webcenter.content.stellent.StellentUtils;
import oracle.webcenter.doclib.internal.config.DocLibADFConfigUtils;
import oracle.webcenter.content.integration.federated.internal.ContentContextHelper;

import portal.Global;
import portal.UtilsContent;

public class DecriptionImageServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    private static final long DEFAULT_EXPIRE_TIME = 604800000L;
    private IdcClient idcClient;
    private String connectionName;
    private String property = null;
    private String nodeID = null;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
            connectionName = DocLibADFConfigUtils.getPrimaryConnectionName();
            idcClient = StellentUtils.getIdcClient(connectionName);


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**Process the HTTP doGet request.
     */
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        response.setContentType(CONTENT_TYPE);
        String srurl = request.getRequestURI();
        String strpara = "";
        if (request.getQueryString() != null)
            strpara = request.getQueryString();
        if (request.getParameter("property") != null)
            property = request.getParameter("property");
        if (request.getParameter("property") != null)
            nodeID = request.getParameter("nodeID");
        if (property != null && nodeID != null &&
            property.equals("IdcAlternateFile"))
            try {
                URLConnection uc = getAlternateFile(nodeID);
                if (uc != null && uc.getContentType().contains("image/")) {
                    getDicriptionImage(uc,response);
                    
                }
            } catch (RepositoryException e) {
                e.printStackTrace();
            }


    }

    /**Process the HTTP doPost request.
     */
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        doGet(request, response);
    }

    /**Process the HTTP doPut request.
     */
    public void doPut(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
    }

    /**Process the HTTP doDelete request.
     */
    public void doDelete(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException,
                                                              IOException {
    }

    /**
     * @creator
     * @comment
     * @param dID
     * @return
     * @throws IOException
     * @throws RepositoryException
     * @throws IllegalArgumentException
     * @throws ServletException
     */
    private URLConnection getAlternateFile(String dID) throws IOException,
                                                              RepositoryException,
                                                              IllegalArgumentException,
                                                              ServletException {

        URLConnection uc = null;
        ContentContext contentContext;

        contentContext = ContentContextHelper.getContentContext();

        INodeManager nodeManager = ContentManagerFactory.getNodeManager();

        IUCMContext.DocRevisionSelectionMethod revisionSelectionMethod;

        revisionSelectionMethod =
                IUCMContext.DocRevisionSelectionMethod.LATEST_RELEASED;

        contentContext.setParameter(IUCMContext.DOC_REVISION_SELECTION_METHOD_KEY,
                                    revisionSelectionMethod);

        ID id = ID.fromString(dID);

        Node node = nodeManager.getNodeByUUID(contentContext, id);

        //lay Alternate file
        Property prop = node.getProperty("idcRenditions");

        Value vl = prop.getValue();

        //lay noi dung file Alternate
        BinaryValue bnrvl =
            vl.getNestedValue()[0].getValues()[0].getBinaryValue();
        String strvl = vl.getNestedValue()[2].getValues()[0].getStringValue();
        URL u = new URL(strvl);
        uc = u.openConnection();

        return uc;


    }

    /**
     * @creator
     * @comment
     * @param uc
     * @param response
     * @throws IOException
     */
    private void getDicriptionImage(URLConnection uc,
                                    HttpServletResponse response) throws IOException {
        //        String contentType = uc.getContentType();
        //        int contentLength = uc.getContentLength();
        //        InputStream raw = uc.getInputStream();
        //        InputStream in = new BufferedInputStream(raw);
        //        byte[] data = new byte[contentLength];
        //        int bytesRead = 0;
        //        int offset = 0;
        //        while (offset < contentLength) {
        //            bytesRead = in.read(data, offset, data.length - offset);
        //            if (bytesRead == -1)
        //                break;
        //            offset += bytesRead;
        //        }
        //        in.close();
        //
        //        ByteArrayInputStream iStream = new ByteArrayInputStream(data);
        //
        //
        //        // Determine the length of the content data.
        //        // In our simple example, I can get the length from the hard-coded byte array.
        //        // If you're getting your imaqe from a database or file,
        //        // you'll need to adjust this code to do what is appropriate:
        //        //int length = SampleImage.sampleImage.length;
        //
        //        // Hard-coded for a GIF image - see text.
        //        response.setContentType("html");
        //        response.setContentLength(contentLength);
        //
        //        // Get the output stream from our response object, so we
        //        // can write our image data to the client:
        //        ServletOutputStream oStream = response.getOutputStream();
        //
        //        // Now, loop through buffer reads of our content, and send it to the client:
        //        byte[] buffer = new byte[1024];
        //        int len;
        //        while ((len = iStream.read(buffer)) != -1) {
        //            oStream.write(buffer, 0, len);
        //        }
        //
        //        // Now that we've sent the image data to the client, close down all the resources:
        //        iStream.close();
        //
        //        oStream.flush();
        //        oStream.close();
        int contentLength = uc.getContentLength();
        InputStream raw = uc.getInputStream();
        byte[] buffer = new byte[1024];
        int size = 0;
        response.setContentType(uc.getContentType());
        response.setContentLength(contentLength);
        //long expiry = new Date().getTime() + ;                   
        //response.setDateHeader("Expires", DEFAULT_EXPIRE_TIME);
        response.setDateHeader("Expires", System.currentTimeMillis(  ) + 24*60*60*1000);
        response.setHeader("Cache-Control", "max-age=3600" );
        ServletOutputStream oStream = response.getOutputStream();
        while ((size = raw.read(buffer)) != -1) {
            oStream.write(buffer, 0, size);
        }
        raw.close();

        oStream.flush();
        oStream.close();
    }
}
